<template>
    <div class="achievement-detail-container" v-loading="loading">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span class="card-title">成果详情</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">
                    返回
                </el-button>
            </div>

            <div v-if="achievementInfo.id" class="detail-content">
                <!-- 基本信息 -->
                <div class="info-section">
                    <h3 class="section-title">基本信息</h3>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="info-item">
                                <label class="info-label">成果标题：</label>
                                <span class="info-value">{{ achievementInfo.title }}</span>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="info-item">
                                <label class="info-label">成果类型：</label>
                                <el-tag :type="getTypeTagType(achievementInfo.achievementType)">
                                    {{ getTypeLabel(achievementInfo.achievementType) }}
                                </el-tag>
                            </div>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="info-item">
                                <label class="info-label">申报学生：</label>
                                <span class="info-value">{{ achievementInfo.studentName }}</span>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="info-item">
                                <label class="info-label">学号：</label>
                                <span class="info-value">{{ achievementInfo.account }}</span>
                            </div>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="info-item">
                                <label class="info-label">所属院系：</label>
                                <span class="info-value">{{ achievementInfo.department }}</span>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="info-item">
                                <label class="info-label">专业：</label>
                                <span class="info-value">{{ achievementInfo.major }}</span>
                            </div>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div class="info-item">
                                <label class="info-label">绑定课程：</label>
                                <span class="info-value">{{ achievementInfo.courseName || '无' }}</span>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="info-item">
                                <label class="info-label">所属学期：</label>
                                <span class="info-value">{{ achievementInfo.semester || '无' }}</span>
                            </div>
                        </el-col>
                    </el-row>

                    <div class="info-item">
                        <label class="info-label">成果级别：</label>
                        <el-tag v-if="achievementInfo.level" :type="getLevelTagType(achievementInfo.level)"
                            style="margin-right: 8px;">
                            {{ getLevelLabel(achievementInfo.level) }}
                        </el-tag>
                        <span v-else class="info-value">无</span>
                    </div>

                    <div class="info-item">
                        <label class="info-label">提交时间：</label>
                        <span class="info-value">{{ achievementInfo.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')
                        }}</span>
                    </div>
                </div>

                <!-- 成果描述 -->
                <div class="info-section">
                    <h3 class="section-title">成果描述</h3>
                    <div class="description-content">
                        {{ achievementInfo.description }}
                    </div>
                </div>


                <!-- 成果附件 -->
                <div v-if="achievementInfo.attachments && achievementInfo.attachments.length > 0" class="info-section">
                    <h3 class="section-title">成果附件</h3>
                    <div class="attachment-list">
                        <div v-for="(file, index) in achievementInfo.attachments" :key="index" class="attachment-item">
                            <div class="file-info">
                                <i :class="getFileIcon(file.fileType)" class="file-icon"></i>
                                <div class="file-details">
                                    <div class="file-name">{{ file.name }}</div>
                                    <div class="file-meta">
                                        <span class="file-size">{{ formatFileSize(file.size) }}</span>
                                        <span class="file-type">{{ file.fileType && file.fileType.toUpperCase()
                                        }}</span>
                                    </div>
                                </div>
                            </div>
                            <el-button type="primary" size="small" icon="el-icon-download"
                                @click="handleDownloadFile(file)">
                                下载
                            </el-button>
                        </div>
                    </div>
                </div>

                <!-- 审核流程 -->
                <div class="info-section">
                    <h3 class="section-title">审核流程</h3>
                    <el-steps :active="getStepActive()" finish-status="success" align-center>
                        <el-step title="学生提交"
                            :description="achievementInfo.createTime | parseTime('{y}-{m}-{d} {h}:{i}')">
                            <i slot="icon" class="el-icon-edit"></i>
                        </el-step>
                        <el-step title="教师审核" :status="getTeacherStepStatus()"
                            :description="getTeacherStepDescription()">
                            <i slot="icon" class="el-icon-user"></i>
                        </el-step>
                        <el-step title="管理员审批" :status="getAdminStepStatus()" :description="getAdminStepDescription()">
                            <i slot="icon" class="el-icon-s-check"></i>
                        </el-step>
                    </el-steps>
                </div>

                <!-- 审核意见 -->
                <div v-if="hasReviewComments()" class="info-section">
                    <h3 class="section-title">审核意见</h3>

                    <!-- 审批流程 -->
                    <div v-for="approval in achievementInfo.approvals" :key="approval.id" class="review-comment">
                        <div class="comment-header">
                            <el-tag :type="getApprovalStatusTagType(approval.approvalStatus)">
                                {{ getApprovalTypeLabel(approval.approvalType) }}：{{
                                    getApprovalStatusLabel(approval.approvalStatus) }}
                            </el-tag>
                            <span class="comment-time">{{ approval.createTime | parseTime('{y}-{m}-{d} {h}:{i}')
                            }}</span>
                        </div>
                        <div class="comment-content">
                            <div><strong>审核人：</strong>{{ approval.teacherName }}</div>
                            <div v-if="approval.comment"><strong>审核意见：</strong>{{ approval.comment }}</div>
                        </div>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div v-if="showActions()" class="action-section">
                    <el-button v-if="canEdit()" type="warning" icon="el-icon-edit" @click="handleEdit">
                        编辑成果
                    </el-button>
                    <el-button v-if="canDelete()" type="danger" icon="el-icon-delete" @click="handleDelete">
                        删除成果
                    </el-button>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script>
import { getAchievementDetail, deleteAchievement } from '@/api/achievement'
import { parseTime } from '@/utils'

export default {
    name: 'AchievementDetail',
    filters: {
        parseTime(time, pattern) {
            return parseTime(time, pattern)
        }
    },
    data() {
        return {
            loading: false,
            achievementId: null,
            achievementInfo: {},
            currentUser: this.$store.getters.userInfo || {}
        }
    },
    created() {
        this.achievementId = this.$route.params.id
        if (this.achievementId) {
            this.getAchievementDetail();
        }
    },
    methods: {
        async getAchievementDetail() {
            this.loading = true
            try {
                const res = await getAchievementDetail(this.achievementId)
                this.achievementInfo = res.data
            } catch (error) {
                console.error('获取成果详情失败:', error);
            } finally {
                this.loading = false
            }
            /* // 模拟数据
            setTimeout(() => {
                const mockData = {
                    1: {
                        id: 1,
                        title: '基于深度学习的图像识别算法研究',
                        achievementType: 1,
                        level: 1,
                        courseName: '人工智能导论',
                        semester: '2024-2025-1',
                        status: 3,
                        description: '本研究提出了一种基于深度学习的图像识别算法，通过改进卷积神经网络结构，显著提升了图像分类的准确率。该算法在多个公开数据集上进行了验证，相比传统方法准确率提升了15%以上。研究成果对计算机视觉领域具有重要的理论意义和实用价值。',
                        remarks: '该研究得到了国家自然科学基金的支持，相关论文已投稿至顶级期刊。',
                        studentName: '张三',
                        studentNumber: '2021001001',
                        department: '计算机科学与技术学院',
                        major: '计算机科学与技术',
                        createTime: '2024-10-15 14:30:00',
                        teacherName: '李教授',
                        teacherReviewTime: '2024-10-17 16:30:00',
                        teacherReviewComment: '该研究具有较高的学术价值，实验设计合理，结果可信，建议通过初审。',
                        adminName: '王主任',
                        adminReviewTime: '2024-10-19 10:15:00',
                        adminReviewComment: '经终审，该成果达到国家级水平，研究内容新颖，技术路线清晰，予以通过并给予优秀等级。',
                        achievementLevel: '优秀',
                        rewardPoints: 50,
                        approvals: [
                            {
                                id: 1,
                                achievementId: 1,
                                approverId: 2,
                                approvalType: 1,
                                approvalStatus: 1,
                                comment: '该研究具有较高的学术价值，实验设计合理，结果可信，建议通过初审。',
                                createTime: '2024-10-17 16:30:00',
                                updateTime: '2024-10-17 16:30:00',
                                deleted: 0,
                                teacherName: '李教授'
                            },
                            {
                                id: 2,
                                achievementId: 1,
                                approverId: 3,
                                approvalType: 2,
                                approvalStatus: 1,
                                comment: '经终审，该成果达到国家级水平，研究内容新颖，技术路线清晰，予以通过并给予优秀等级。',
                                createTime: '2024-10-19 10:15:00',
                                updateTime: '2024-10-19 10:15:00',
                                deleted: 0,
                                teacherName: '王主任'
                            }
                        ],
                        fileUrl: JSON.stringify([
                            {
                                name: '论文全文.pdf',
                                url: 'https://example.com/paper1.pdf',
                                fileType: 'pdf',
                                size: 2048576
                            },
                            {
                                name: '实验数据.xlsx',
                                url: 'https://example.com/data1.xlsx',
                                fileType: 'xlsx',
                                size: 512000
                            }
                        ])
                    },
                    2: {
                        id: 2,
                        title: '智能家居控制系统发明专利',
                        achievementType: 2,
                        level: 2,
                        courseName: '物联网技术',
                        semester: '2024-2025-1',
                        status: 1,
                        description: '本专利提出了一种基于物联网技术的智能家居控制系统，通过集成多种传感器和智能控制算法，实现了家居设备的自动化管理和远程控制。系统具有节能环保、操作简便、安全可靠等特点。',
                        remarks: '该专利已通过初步审查，正在等待实质审查结果。',
                        studentName: '李四',
                        studentNumber: '2021001002',
                        department: '物联网工程学院',
                        major: '物联网工程',
                        createTime: '2024-10-10 09:15:00',
                        teacherName: '张教授',
                        teacherReviewTime: '2024-10-12 14:20:00',
                        teacherReviewComment: '专利申请材料完整，技术方案具有一定的创新性，符合申报要求。',
                        approvals: [
                            {
                                id: 3,
                                achievementId: 2,
                                approverId: 2,
                                approvalType: 1,
                                approvalStatus: 1,
                                comment: '专利申请材料完整，技术方案具有一定的创新性，符合申报要求。',
                                createTime: '2024-10-12 14:20:00',
                                updateTime: '2024-10-12 14:20:00',
                                deleted: 0,
                                teacherName: '张教授'
                            }
                        ],
                        fileUrl: JSON.stringify([
                            {
                                name: '专利申请书.pdf',
                                url: 'https://example.com/patent1.pdf',
                                fileType: 'pdf',
                                size: 1024000
                            }
                        ])
                    }
                }

                this.achievementInfo = mockData[this.achievementId] || mockData[1]

                // 处理附件数据
                if (this.achievementInfo.fileUrl) {
                    try {
                        this.achievementInfo.attachments = JSON.parse(this.achievementInfo.fileUrl)
                    } catch (e) {
                        console.error('解析附件数据失败:', e)
                        this.achievementInfo.attachments = []
                    }
                } else {
                    this.achievementInfo.attachments = []
                }

                // 处理标签数据
                if (this.achievementInfo.tags && typeof this.achievementInfo.tags === 'string') {
                    try {
                        this.achievementInfo.tags = JSON.parse(this.achievementInfo.tags)
                    } catch (e) {
                        this.achievementInfo.tags = []
                    }
                }

                this.loading = false
            }, 1000) */
        },

        goBack() {
            this.$router.go(-1)
        },

        handleDownloadFile(file) {
            if (file && file.url) {
                window.open(file.url, '_blank')
            }
        },

        handleEdit() {
            this.$router.push(`/achievement/apply?id=${this.achievementId}`)
        },

        async handleDelete() {
            try {
                await this.$confirm(`确定要删除成果"${this.achievementInfo.title}"吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })

                const res = await deleteAchievement(this.achievementId)
                if (res.code === 200) {
                    this.$message.success('删除成功')
                    this.$router.push('/achievement/my-achievements')
                } else {
                    this.$message.error(res.msg || '删除失败')
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除成果失败:', error)
                    this.$message.error('删除失败')
                }
            }
        },

        showActions() {
            // 只有学生本人可以看到操作按钮
            return this.currentUser.id === this.achievementInfo.studentId
        },

        canEdit() {
            // 只有待教师审核或被拒绝的成果可以编辑
            const status = this.achievementInfo.status
            return status === 0 || status === 2 || status === 5
        },

        canDelete() {
            // 只有待教师审核的成果可以删除
            return this.achievementInfo.status === 0
        },

        hasReviewComments() {
            return this.achievementInfo.approvals && this.achievementInfo.approvals.length > 0
        },

        getStepActive() {
            const teacherApproval = this.getTeacherApproval()
            const adminApproval = this.getAdminApproval()

            if (adminApproval) return 3 // 管理员已审批
            if (teacherApproval) return 2 // 教师已审核
            return 1 // 学生已提交，待教师审核
        },

        getTeacherStepStatus() {
            const teacherApproval = this.getTeacherApproval()
            if (!teacherApproval) return 'wait'
            if (teacherApproval.approvalStatus === 1) return 'finish'
            if (teacherApproval.approvalStatus === 2) return 'error'
            return 'process'
        },

        getTeacherStepDescription() {
            const teacherApproval = this.getTeacherApproval()
            if (!teacherApproval) return '待审核'
            if (teacherApproval.approvalStatus === 1) return parseTime(teacherApproval.createTime, '{y}-{m}-{d} {h}:{i}')
            if (teacherApproval.approvalStatus === 2) return parseTime(teacherApproval.createTime, '{y}-{m}-{d} {h}:{i}')
            return ''
        },

        getAdminStepStatus() {
            const adminApproval = this.getAdminApproval()
            if (!adminApproval) {
                // 如果教师审核通过了，管理员审批为待处理状态
                const teacherApproval = this.getTeacherApproval()
                if (teacherApproval && teacherApproval.approvalStatus === 1) return 'process'
                return 'wait'
            }
            if (adminApproval.approvalStatus === 1) return 'finish'
            if (adminApproval.approvalStatus === 2) return 'error'
            return 'process'
        },

        getAdminStepDescription() {
            const adminApproval = this.getAdminApproval()
            if (!adminApproval) {
                const teacherApproval = this.getTeacherApproval()
                if (teacherApproval && teacherApproval.approvalStatus === 1) return '待审批'
                return ''
            }
            if (adminApproval.approvalStatus === 1) return parseTime(adminApproval.createTime, '{y}-{m}-{d} {h}:{i}')
            if (adminApproval.approvalStatus === 2) return parseTime(adminApproval.createTime, '{y}-{m}-{d} {h}:{i}')
            return ''
        },

        // 获取教师审批记录
        getTeacherApproval() {
            if (!this.achievementInfo.approvals) return null
            return this.achievementInfo.approvals.find(approval => approval.approvalType === 1)
        },

        // 获取管理员审批记录
        getAdminApproval() {
            if (!this.achievementInfo.approvals) return null
            return this.achievementInfo.approvals.find(approval => approval.approvalType === 2)
        },

        // 获取审批类型标签
        getApprovalTypeLabel(type) {
            const typeMap = {
                1: '教师审核',
                2: '管理员审批'
            }
            return typeMap[type] || '未知'
        },

        // 获取审批状态标签
        getApprovalStatusLabel(status) {
            const statusMap = {
                1: '通过',
                2: '拒绝'
            }
            return statusMap[status] || '未知'
        },

        // 获取审批状态标签类型
        getApprovalStatusTagType(status) {
            const typeMap = {
                1: 'success',
                2: 'danger'
            }
            return typeMap[status] || 'info'
        },

        getTypeLabel(type) {
            const typeMap = {
                1: '论文',
                2: '专利',
                3: '竞赛证书',
                4: '项目计划',
                5: '其他'
            }
            return typeMap[type] || '未知'
        },

        getTypeTagType(type) {
            const typeMap = {
                1: 'primary',
                2: 'success',
                3: 'warning',
                4: 'info',
                5: 'default'
            }
            return typeMap[type] || 'default'
        },

        getTeacherStatusLabel(status) {
            const statusMap = {
                0: '待审核',
                1: '已通过',
                2: '已拒绝'
            }
            return statusMap[status] || '未知'
        },

        getTeacherStatusTagType(status) {
            const statusMap = {
                0: 'info',
                1: 'success',
                2: 'danger'
            }
            return statusMap[status] || 'default'
        },

        getAdminStatusLabel(status) {
            const statusMap = {
                3: '待审批',
                4: '已通过',
                5: '已拒绝'
            }
            return statusMap[status] || '未知'
        },

        getAdminStatusTagType(status) {
            const statusMap = {
                3: 'warning',
                4: 'success',
                5: 'danger'
            }
            return statusMap[status] || 'default'
        },

        getFileIcon(fileType) {
            const iconMap = {
                'pdf': 'el-icon-document',
                'doc': 'el-icon-document',
                'docx': 'el-icon-document',
                'jpg': 'el-icon-picture',
                'jpeg': 'el-icon-picture',
                'png': 'el-icon-picture',
                'gif': 'el-icon-picture'
            }
            return iconMap[fileType] || 'el-icon-document'
        },

        getLevelLabel(level) {
            const levelMap = {
                1: '国家级',
                2: '省级',
                3: '市级',
                4: '校级'
            }
            return levelMap[level] || '未知'
        },
        getLevelTagType(level) {
            const levelMap = {
                1: 'danger',   // 国家级 - 红色
                2: 'warning',  // 省级 - 橙色
                3: 'primary',  // 市级 - 蓝色
                4: 'success'   // 校级 - 绿色
            }
            return levelMap[level] || 'info'
        },
        formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes'
            const k = 1024
            const sizes = ['Bytes', 'KB', 'MB', 'GB']
            const i = Math.floor(Math.log(bytes) / Math.log(k))
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
        }
    }
}
</script>

<style lang="scss" scoped>
.achievement-detail-container {
    padding: 20px;
}

.box-card {
    max-width: 1200px;
    margin: 0 auto;
}

.card-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

.detail-content {
    padding: 20px 0;
}

.info-section {
    margin-bottom: 30px;

    &:last-child {
        margin-bottom: 0;
    }
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 2px solid #409EFF;
}

.info-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;

    .info-label {
        min-width: 100px;
        font-weight: 500;
        color: #606266;
        margin-right: 10px;
    }

    .info-value {
        flex: 1;
        color: #303133;
    }
}

.tag-list {
    flex: 1;
}

.description-content {
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    line-height: 1.6;
    color: #303133;
    white-space: pre-wrap;
}

.attachment-list {
    .attachment-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px;
        margin-bottom: 10px;
        background-color: #f5f7fa;
        border-radius: 4px;
        border: 1px solid #e4e7ed;

        &:last-child {
            margin-bottom: 0;
        }

        .file-info {
            display: flex;
            align-items: center;
            flex: 1;

            .file-icon {
                font-size: 24px;
                color: #409EFF;
                margin-right: 15px;
            }

            .file-details {
                .file-name {
                    font-weight: 500;
                    color: #303133;
                    margin-bottom: 5px;
                }

                .file-meta {
                    font-size: 12px;
                    color: #909399;

                    span {
                        margin-right: 15px;
                    }
                }
            }
        }
    }
}

.review-comment {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border-left: 4px solid #409EFF;

    &:last-child {
        margin-bottom: 0;
    }

    .comment-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .comment-time {
            font-size: 12px;
            color: #909399;
        }
    }

    .comment-content {
        color: #303133;
        line-height: 1.6;
        white-space: pre-wrap;
    }
}

.action-section {
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;

    .el-button {
        margin: 0 10px;
    }
}

.el-steps {
    margin: 20px 0;
}
</style>